import { _decorator, Component, Node, RigidBody, v3 } from 'cc';
import { PhyGroup } from './EliminateSlotTrigger';
import { MeshCollider } from 'cc';
import { MeshRenderer } from 'cc';
import { Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EliminateToy')
export class EliminateToy extends Component {

    /** 是否可以被捡起 */
    public canTouch: boolean = true;

    private _toyId: number;
    public set toyId(v: number) {
        this._toyId = v;
    }
    public get toyId() {
        return this._toyId;
    }

    /** 当前所在消除槽子的位置索引 */
    public slotIndex: number = -1;

    public originScale: Vec3 = null;

    /** 是否进入触发器 */
    public enterSlot: boolean = false;

    private _moving: boolean = false;
    private _targetPos: Vec3 = v3(0, 0, 0);
    private _moveSpeed: number = 100;

    protected __preload(): void {
    }

    moveToTargetPos(targetPos: Vec3) {
        this._moving = true;
        const offset = this.node.position.clone().subtract(targetPos);
        if (offset.x > 0) {
            this._moveSpeed = 100;
        } else {
            this._moveSpeed = -100;
        }
        this._targetPos = targetPos;
    }

    protected onLoad(): void {
        this.originScale = this.node.getScale();
        const rb = this.node.getComponent(RigidBody);
        const renderComp = this.node.getComponentInChildren(MeshRenderer);
        // renderComp.materials[0].uuid;

        // renderComp.mesh.name
        const meshCollider = this.node.getComponent(MeshCollider);
        meshCollider && (meshCollider.convex = true);
        rb.group = PhyGroup.TOYS;
        rb.mass = 3;
        rb.useCCD = true;
    }

    start() {
        const rb = this.node.getComponent(RigidBody);
        rb.group = PhyGroup.TOYS;
        // rb.useCCD = true;
        rb.linearDamping = 0.1;
        rb.angularDamping = 0.6;
    }

    update(dt: number) {
        // 水平移动
        if (this._moving) {
            this.node.getPosition().add(v3(this._moveSpeed * dt, 0, 0));
            if ( this.node.getPosition().x - this._targetPos.x >= 0 && this._moveSpeed > 0) {
                this.node.setPosition(this._targetPos);
                this._moving = false;
            } else if(this._moveSpeed < 0 && this._targetPos.x - this.node.getPosition().x >= 0) {
                this.node.setPosition(this._targetPos);
                this._moving = false;
            }
        }
    }
}

